<?php
namespace App\Repositories;

use App\Comment;
use App\Repositories\BaseRepository;
use App\Scopes\StatusScope;
use App\User;

class CommentRepository {
	use BaseRepository;

	protected $model, $table_name, $user;

	public function __construct(Comment $comment, User $user) {
		$this->model = $comment;
		$this->user = $user;
		$this->table_name = 'comments';
	}

	protected function searchColumn($query, $where) {
		return $query->when(array_key_exists('content', $where), function ($query) use ($where) {
			return $query->where('content', 'like', "%{$where['content']}%");
		})->when(array_key_exists('name', $where), function ($query) use ($where) {
			return $query->whereHas('user', function ($query) use ($where) {
				return $query->withoutGlobalScope(StatusScope::class)->where('name', 'like', "%{$where['name']}%")->orWhere('nick_name', 'like', "%{$where['name']}%");
			});
		})->when(array_key_exists('title', $where), function ($query) use ($where) {
			return $query->whereHas('item', function ($query) use ($where) {
				return $query->withoutGlobalScope(StatusScope::class)->where('title', 'like', "%{$where['title']}%");
			});
		});
	}

	public function store($input) {
		$reply = new \StdClass();
		if (strpos($input['content'], '@') !== -1) {
			$array = explode(' ', substr($input['content'], 1));
			if (count($array) > 1) {
				$name = array_shift($array);
				$user = $this->user->where('name', $name)->select('id', 'avatar')->first();
				if ($user) {
					$input['reply_id'] = $user['id'];
					$input['content'] = implode(' ', $array);
					$reply = array_merge($user->toArray(), compact('name'));
				}
			}
		}
		$comment = $this->save($this->model, $input)->toArray();
		//注销部分数据
		unset($comment['item_id']);
		unset($comment['reply_id']);
		unset($comment['updated_at']);
		unset($comment['user_id']);

		return array_merge($comment, compact('reply'));
	}

	public function getRandReply() {
		$all_ids = $this->model->select('id')->whereHas('item', function ($query) {
			return $query->has("cate");
		})->get()->toArray();
		if (count($all_ids) > 8) {
			$ids = array_rand(array_column($all_ids, 'id'), 8);
		} else {
			$ids = array_column($all_ids, 'id');
		}
		return $this->model->whereIn('id', $ids)->get();
	}
}